//
//  AFFLModeBase.m
//  AnyfishApp
//
//  Created by Bob Lee on 15/8/4.
//  Copyright (c) 2015年 Anyfish. All rights reserved.
//

#import "AFFLModeBase.h"
@implementation AFFLModeBase



- (AFFLModeBase*)copySelf {
    NSArray *arrCopy = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:@[self]]];
    
    return [arrCopy firstObject];
}

@end


@implementation AFFLModeTab

- (id)copy {
    return self;
}

- (NSString*)fileNameConfig_Full {
    return [NSString stringWithFormat:@"%@/Tab_config.txt", [self configPath_Full]];
}


- (NSString*)title {
    if(self.titleReplace)
        return self.titleReplace;
    
    return _title;
}

@end


#pragma mark 以下是缓存定义

@implementation AFFLModeCache

- (NSString*)imgNameNew {
    return _imgName;
}

- (NSString*)configPath_Full {
    return kSetting.path_Location;
}

- (NSString*)fileNameConfig_Full {
    return [NSString stringWithFormat:@"%@/config.txt", [self configPath_Full]];
}

- (BOOL)saveImage:(NSData*)image {
    if(image==nil)return NO;
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    _imgName = self.imgName;
    NSString *fileName = [NSString stringWithFormat:@"%@/%@.png", [self configPath_Full], _imgName];
    [defaultManager createFileAtPath:fileName contents:image attributes:nil];
    return YES;
}

- (NSString*)getImageNameFull {
    return [NSString stringWithFormat:@"%@/%@.png", [self configPath_Full], self.imgName];
}

- (NSData*)getImage {
    NSData *img = nil;
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    NSString *fileName = [self getImageNameFull];
    if([defaultManager fileExistsAtPath:fileName]){
        img = [NSData dataWithContentsOfFile:fileName];
    }
    
    return img;
}

@end


#import <CoreLocation/CoreLocation.h>
static CLPlacemark *curPlacemark; ///< 当前位置描述每小时更新
static BOOL isPullMark;
static NSMutableArray *mArrAddress; ///< 缓存地址，启动时读取一次，每次程序转后台尝试保存一次

@implementation AFFLModeAddress

- (NSString*)imgName {
    return [NSString stringWithFormat:@"%d_%d_%lld", _longitude, _latitude, _landCode];
}

+ (AFFLModeAddress*)getCacheAddressLand:(U64)land{
    return [self getCacheAddress:0 lat:0 land:land];
}

+ (AFFLModeAddress*)getCacheAddress:(S32)lon lat:(S32)lat {
    return [self getCacheAddress:lon lat:lat land:0];
}

+ (AFFLModeAddress*)getCacheAddress:(S32)lon lat:(S32)lat land:(U64)land{
    AFFLModeAddress *addr = nil, *addrRe = nil;
    NSMutableArray *mArr = [AFFLModeAddress loadAddress];
    @synchronized(mArr) {
        for(AFFLModeAddress *address in mArr){
            if(land>0){
                if(address.landCode == land){
                    addr=address;
                    break;
                }
            }else {
                if(address.longitude == lon && address.latitude == lat){
                    addr = address;
                    break;
                }else if(addrRe==nil){
                    // 计算距离50m内不重复获取
                    double distance = 0;
                    if(distance <=50.00){
                        addrRe = address;
                    }
                }
            }
        }
        
        addr = addr?addr:addrRe;
        
        if(addr && curPlacemark){
            NSString *desc = addr.desc;
            NSDictionary *dic = curPlacemark.addressDictionary;
            
            if([addr.countryCode isEqualToString:[dic stringForKey:@"CountryCode"]] && addr.country){
                // 去掉国家
                desc = [desc stringByReplacingOccurrencesOfString:addr.country withString:@""];
            }
            
            if([[dic objectForKey:@"State"] isEqualToString:addr.province]){
                // 去掉省
                desc = [desc stringByReplacingOccurrencesOfString:addr.province withString:@""];
            }
            
            addr.desc = desc;
        }
        
        if(curPlacemark==nil){
            [self updatePlacemark];
        }
    }
    
    return addr;
}

+ (void)setCacheAddress:(AFFLModeAddress*)addr{
    if(addr){
        NSMutableArray *mArr = [AFFLModeAddress loadAddress];
        
        @synchronized(mArr) {
            // 判断如果原来有就干掉
            AFFLModeAddress *temp = nil;
            for(AFFLModeAddress *add in mArr){
                if(addr.landCode>0){
                    if(add.landCode == addr.landCode){
                        temp=add;
                        break;
                    }
                }else {
                    if(add.longitude == addr.longitude && add.latitude == addr.latitude){
                        temp = add;
                        break;
                    }else {
                        // 计算距离50m内不重复获取
                        double distance = 0;
                        if(distance <=50.00){
                            temp = add;
                            break;
                        }
                    }
                }
            }
            
            if(temp && mArr.count>0){
                if(![NSString isNilOrEmpty:addr.desc]){
                    temp.desc = addr.desc;
                    temp.country = addr.country;
                    temp.province = addr.province;
                    temp.city = addr.city;
                    temp.subLocality = addr.subLocality;
                    temp.subThoroughfare = addr.subThoroughfare;
                    temp.street = addr.street;
                    temp.countryCode = addr.countryCode;
                    
                }else {
                    // 图片
                    temp.imgNameAddr = addr.imgNameAddr;
                    temp.imgName = addr.imgName;
                }
            }
            
            if(temp && [temp.desc isEqualToString:@"ICON云端"]){
                NSLog(@"地址发生问题");
            }
            
            [mArr addObject:addr];
        }
    }
}

+ (void)updatePlacemark {
    if(isPullMark)
        return;
    
    isPullMark = YES;
}

+ (NSMutableArray*)loadAddress {
    if(mArrAddress==nil){
        mArrAddress = [NSMutableArray array];
        
        AFFLModeAddress *addr = [[AFFLModeAddress alloc] init];

    }
    
    return mArrAddress;
}

+ (void)saveAddress {
//    if(mArrAddress && mArrAddress.count>0){
//        @synchronized(mArrAddress) {
//            AFFLModeAddress *addr = [[AFFLModeAddress alloc] init];
//            NSArray *top = [AFFLModeAddress keyValuesArrayWithObjectArray:mArrAddress];
//            if(top){
//                NSString *str = [top JSONString];
//                if(str){
//                    [[top JSONString] writeToFile:[addr fileNameConfig_Full] atomically:YES encoding:NSUTF8StringEncoding error:nil];
//                }
//            }
//        }
//    }
}

@end

@implementation AFFLModeUrl

- (NSString*)configPath_Full {
    return kSetting.path_Url;
}

- (NSString*)imgName {

    _imgNameUrl = _imgNameUrl?_imgNameUrl:[NSString stringWithFormat:@"%lld",[NSDate timeMicro]];
    
    return _imgNameUrl;
}

+ (void)updateUrlCache:(AFFDataMedia*)media {

}


@end
